import { PicUploadService } from '@services/picUpload.service';
import { PopoverPage } from '@pages/home/popover/popover';
import { DataService } from '@services/data.service';
import { Component, OnInit, ElementRef, Renderer2, AfterViewChecked, HostBinding } from '@angular/core';
import {
  ModalController,
  NavController,
  PopoverController,
  // NavParams,
} from '@ionic/angular';
import { QRScannerModal } from '@modals/qr-scanner/qr-scanner';
import { HttpService } from '@services/http.service';
import { CacheService } from '@services/cache.service';
import { EmitService } from '@services/emit.service';
import { Router, ActivatedRoute, Params } from '@angular/router';
import * as Hammer from 'hammerjs';
// import { slideToRight } from '../../../ainimate';

// 页面导入
// import { AlarmReportPage } from '../alarm-report/alarm-report';
// import { EnergyPage } from '../energy-consumption/energy';


@Component({
  selector: 'index-group',
  templateUrl: 'page.html',
  styleUrls: ['style.scss'],
  // animations: [   // 这里别忘了！！！
  //   slideToRight
  // ]
})
export class IndexGroupPage implements OnInit, AfterViewChecked {
  // @HostBinding('@routeAnim') state;  // 最后一步！！！
  person = {
    headStyle: {
    },
    headStylebg: {
    }
  };
  params;
  canGoBack = true;
  PList = [];
  TargetList = []; // 集团指标
  canRun = false;  // 是否可滚动
  canReturn = true; // 是否可回滚
  isFinished = false; // 是否滚动完毕
  isLess = false;      // 判断是否是少量的滚动
  companyId;
  userId;
  companyName;
  myCompanys = [];
  cityIndex = 0;   // 初始化选择区域
  cityData;
  isSelected;
  TargetInterval; // 指标定时器
  isDown = false;         // 是否可下拉
  projectList = [];

  // 判断滑动变化
  headerActive = false;
  contentActive = false;
  shadowActive = false;
  bodyActive = false;

  informOption = {
    step: 1,
    timer: 50,
    left: 25,
    right: 10,
  };



  indexDataList = [
    { IndexCode: '105102', IndexName: '严重告警', Data1: 0, Data2: 0, Unit1: '次', isShow: false },
    { IndexCode: '105103', IndexName: '告警及时响应率', Data1: 0, Data2: 0, Unit1: '%', isShow: false },
    { IndexCode: '105104', IndexName: '告警及时恢复率', Data1: 0, Data2: 0, Unit1: '%', isShow: false },
    { IndexCode: '105120', IndexName: 'IOT在线率', Data1: 0, Data2: 0, Unit1: '%', isShow: false },
    { IndexCode: '103016', IndexName: '数据栈', Data1: 0, Data2: 0, isShow: false },
    { IndexCode: '103115', IndexName: '传感器', Data1: 0, Data2: 0, isShow: false },
    { IndexCode: '105137', IndexName: '物联工单完成', Data1: 0, Data2: 0, Unit1: '%', isShow: false },
  ];

  blocInfo = {
    BlocName: '',
    Comprehensive: { Title: '', Evaluation: '', Percent: null },
    BlocBGP: '',
    BlocUrl: '',
    Announcement: '关于开展预交物业费送礼品活动通知',
  };

  constructor(
    private modalCtrl: ModalController,
    private navCtrl: NavController,
    private el: ElementRef,
    private renderer: Renderer2,
    private httpService: HttpService,
    // private navParams: NavParams,
    private dataservice: DataService,
    private cache: CacheService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private popoverCtrl: PopoverController,
    private picUploadService: PicUploadService,
  ) {
    // this.companyId = this.navParams.get('companyId') ? this.navParams.get('companyId')
    //  : this.cache.currentCompany.companyId;
    // this.companyName = this.navParams.get('companyName') ?  this.navParams.get('companyName')
    //  : this.cache.currentCompany.companyName;

    this.activatedRoute.queryParams.subscribe(params => {
      this.params = params;
      this.companyId = params.companyId ? params.companyId : this.cache.currentCompany.companyId;
      this.companyName = params.companyName ? params.companyName : this.cache.currentCompany.companyName;
    });
    if (this.cache.functionPoint.length === 2) {
      this.canGoBack = false;
    }
    this.userId = this.cache.userinfo.userId;
    this.PList = this.cache.functionPoint[this.cache.functionPoint.length - 2].children;
  }

  ngOnInit() {
  }

  ngAfterViewChecked() {
    this.WordResult();
  }

  ionViewWillEnter() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements !== null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'flex';
      });
    }
    this.setHeadAndBack();
    this.init();
  }

  ionViewWillLeave() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements !== null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'none';
      });
    }
    if (this.TargetInterval) {
      clearInterval(this.TargetInterval);
    }
  }

  // 初始化页面数据
  init() {
    const Plist = [];
    const Tlist = [];
    for (let i = 0; i < this.PList.length; i++) {
      if (this.PList[i].menuType === 9) {
        // 平台层指标
        Tlist.push(this.PList[i]);
      } else {
        Plist.push(this.PList[i]);
      }
    }
    this.PList = Plist;
    this.TargetList = Tlist;
    for (let i = 0; i < this.indexDataList.length; i++) {
      for (let j = 0; j < this.TargetList.length; j++) {
        if (this.TargetList[j].menuName === this.indexDataList[i].IndexName) {
          this.indexDataList[i].isShow = true;
        }
      }
    }
    this.getProjectList();
    this.getCompanys();
    this.getTarget();
  }


  getTarget() {
    this.dataservice.getTarget(105102, 2, this.companyId).subscribe(res => {
      // console.log('获取严重告警指标');
      if (res.data) {
        this.indexDataList[0].Data1 = res.data.alarmNum;
      }
    });
    this.dataservice.getTarget(105103, 2, this.companyId).subscribe(res => {
      // console.log('获取告警及时响应率指标');
      if (res.data) {
        this.indexDataList[1].Data1 = Math.round(res.data.rate);
      }
    });
    this.dataservice.getTarget(105104, 2, this.companyId).subscribe(res => {
      // console.log('获取告警及时恢复率指标');
      if (res.data) {
        this.indexDataList[2].Data1 = Math.round(res.data.rate);
      }
    });
    this.dataservice.getTarget(105120, 2, this.companyId).subscribe(res => {
      // console.log('获取IOT在线率指标');
      if (res.data && res.data.totalNum) {
        this.indexDataList[3].Data1 = Math.round((res.data.onlineNum / res.data.totalNum) * 100);
      }
    });
    this.dataservice.getTarget(103016, 2, this.companyId).subscribe(res => {
      // console.log('获取数据栈指标');
      if (res.data) {
        this.indexDataList[4].Data1 = res.data.totalNum - res.data.onlineNum;
        this.indexDataList[4].Data2 = res.data.totalNum;
      }
    });
    this.dataservice.getTarget(103115, 2, this.companyId).subscribe(res => {
      // console.log('获取传感器指标');
      if (res.data) {
        this.indexDataList[5].Data1 = res.data.totalNum - res.data.onlineNum;
        this.indexDataList[5].Data2 = res.data.totalNum;
      }
    });
    this.dataservice.getTarget(105137, 2, this.companyId).subscribe(res => {
      // console.log('获取物联工单完成指标');
      if (res.data && res.data.totalNum) {
        this.indexDataList[6].Data1 = Math.round((res.data.recoveryNum / res.data.totalNum) * 100);
      }
    });
  }

  setHeadAndBack() {
    this.person.headStylebg = { 'background': 'linear-gradient(#54BFF4, #1FB5FF)' };
    this.person.headStyle = { 'background-image': 'url(assets/imgs/default.png)' };
    this.picUploadService.getAvatar().subscribe(imgdata => {
      if (imgdata.isDefault) {
        this.person.headStylebg = { 'background-image': 'linear-gradient(#54BFF4, #1FB5FF)' };
      } else {
        this.person.headStylebg = { 'background-image': 'url(' + imgdata.url + ')' };
      }
      this.person.headStyle = { 'background-image': 'url(' + imgdata.url + ')' };
    });
  }

  /**
   * 获取项目列表
   */
  getProjectList() {
    this.dataservice.getProjects(this.companyId).subscribe(res => {
      if (res.data) {
        const elm = this.el.nativeElement.querySelector('.bottom-part');
        const eln = this.el.nativeElement.querySelector('.area-info');
        if (res.data.companyProjectGroupMode !== 4) {
          if (res.data.defaultGroupInfo) {
            this.projectList = this.groupProject(res.data.defaultGroupInfo, res.data.companyProjectGroupMode);
          }
          if (this.projectList.length) {
            if (this.projectList[this.cityIndex].groups.length / 4 > 3) {
              this.canRun = true;
              this.isLess = false;
              this.renderer.setStyle(elm, 'touch-action', 'none');
            } else {
              this.canRun = false;
              this.isLess = true;
              this.renderer.setStyle(elm, 'touch-action', 'inherit');
              this.renderer.setStyle(eln, 'touch-action', 'inherit');
            }
          }
        } else {
          if (res.data.customizeGroupInfo) {
            const list = [];
            for (const data of res.data.customizeGroupInfo) {
              if (data && data.projectList.length) {
                list.push(data);
              }
            }
            this.projectList = list;
          }
          if (this.projectList.length) {
            for (const data of this.projectList) {
              data.companyProjectGroupMode = 4;
            }
            if (this.projectList[this.cityIndex].projectList.length / 4 > 3) {
              this.canRun = true;
              this.isLess = false;
              this.renderer.setStyle(elm, 'touch-action', 'none');
            } else {
              this.canRun = false;
              this.isLess = true;
              this.renderer.setStyle(elm, 'touch-action', 'inherit');
            }
          }
        }
      }
      if (this.projectList.length > 4) {
        setTimeout(() => {
          // this.cityIndex = 0;
          // const scrollLine = this.el.nativeElement.querySelector('.line');
          // this.renderer.setStyle(scrollLine, 'left', '5%');
          this.Move();
        }, 1000)
      }
    });
  }
  // 项目根据所在区域分组
  groupProject(arr, val: any) {
    const map = {};
    const dest = [];
    const type = ['provinceName', 'cityName', 'districtName'];
    const index = parseInt(val, 10) - 1;
    const typeName = type[index];
    if (arr && arr.length) {
      for (let i = 0; i < arr.length; i++) {
        const ai = arr[i];
        ai.companyProjectGroupMode = val;
        if (!map[ai[typeName]]) {
          dest.push({
            projectId: ai.projectId,
            cityId: ai.cityId,
            cityName: ai[typeName],
            provinceId: ai.provinceId,
            provinceName: ai.provinceName,
            districtId: ai.districtId,
            districtName: ai.districtName,
            companyProjectGroupMode: ai.companyProjectGroupMode,
            groups: [ai]
          });
          map[ai[typeName]] = ai;
        } else {
          for (let j = 0; j < dest.length; j++) {
            const dj = dest[j];
            if (dj[typeName] === ai[typeName]) {
              dj.groups.push(ai);
              break;
            }
          }
        }
      }
    }
    return dest;
  }

  // 获取该用户的公司
  getCompanys() {
    this.cache.companys.subscribe((data) => {
      this.myCompanys = data;
    });
  }

  // 绘制综合态势环图
  drawCircle(value) {
    const canvas = this.el.nativeElement.querySelector('#myCanvas');
    const endAngles = parseFloat(value) * 0.02 * Math.PI - Math.PI / 2;
    const ele = this.el.nativeElement.querySelector('#groupCircle');
    const eleHeight = ele.offsetHeight || 118;

    if (canvas.getContext) {
      const ctx = canvas.getContext('2d');
      ctx.beginPath();
      ctx.strokeStyle = '#5C9DED';
      ctx.lineWidth = 2;
      ctx.lineCap = 'round';
      const circle = {
        x: 150, // 圆心的x轴坐标值
        y: eleHeight * 0.5 + 2, // 圆心的y轴坐标值
        r: eleHeight * 0.5 - 1, // 圆的半径
      };
      ctx.arc(circle.x, circle.y, circle.r, -Math.PI / 2, endAngles, false);
      ctx.stroke();

      this.renderer.setStyle(ele, 'background', 'rgba(255,255,255,.08)');
      this.renderer.setStyle(
        ele,
        'box-shadow',
        '1px 0px 0px rgba(0, 0, 0, .3)'
      );
    }
  }

  scrollHandler(event) {
    const columnTop = event.scrollTop;
    const opacity = columnTop / 186 >= 1 ? 1 : columnTop / 186;
    const topEle = this.el.nativeElement.querySelector('.project-title');
    this.renderer.setStyle(
      topEle,
      'background',
      'rgba(31,181,255,' + opacity + ')'
    );
  }

  // 扫码
  scan() {
    this.modalCtrl.create({ component: QRScannerModal }).then(videoModal => {
      videoModal.present();
    });
  }

  async Search(i) {
    const params = {
      companyId: this.companyId,
      companyName: this.companyName
    };
    const popover = await this.popoverCtrl.create({
      component: PopoverPage,
      componentProps: {
        type: i,
        Page: 1
      },
      backdropDismiss: false,
      cssClass: 'home-popover'
    });
    popover.present();
    const res = await popover.onDidDismiss();
    const scrollLine = this.el.nativeElement.querySelector('.line');
    const scrollElm = this.el.nativeElement.querySelector('.area-region');
    if (res.data) {
      if (this.bodyActive && this.isFinished) {
        this.isSelected = true;
      } else {
        this.isSelected = false;
      }
      this.cityIndex = 0;
      if (scrollLine) {
        this.renderer.setStyle(scrollLine, 'left', 25 * this.cityIndex + 5 + '%');
        this.renderer.setStyle(scrollLine, 'transition', '1s');
      }
      if (scrollElm) {
        this.renderer.setStyle(scrollElm, 'left', '0');
        this.renderer.setStyle(scrollElm, 'transition', '1s');
      }
      const data = res.data;
      if (data && data.item) {
        switch (data.type) {
          case '1':
            this.cache.currentCompany = data.item;
            this.companyId = data.item.companyId;
            this.companyName = data.item.companyName;
            this.init();
            break;

          case '2':
            this.cache.currentProject = data.item;
            this.navCtrl.navigateForward(['tabs/home/indexProject'], {
              queryParams: {
                type: data.type,
                companyId: params.companyId,
                companyName: params.companyName
              }
            });
            break;

          case '3':
            this.goPage(data.item);
            break;

        }
      }
    }

  }

  goPage(data) {
    if (data.url) {
      this.navCtrl.navigateForward(['tabs/home/' + data.url], {
        queryParams: {
          page: 1
        }
      });
    } else {
      console.log(data.menuName + ',该功能点url不正确或未配置');
    }
  }

  /**
   * 跳转项目页
   */
  goProject(data) {
    this.cache.currentProject = data;
    this.navCtrl.navigateForward(['tabs/home/indexProject'], {
      queryParams: data
    });
  }

  toCity(index, data) {
    this.cityIndex = index;
    const scrollElm = this.el.nativeElement.querySelector('.area-region');
    const scrollModule = this.el.nativeElement.querySelector('.region-module');
    const scrollLine = this.el.nativeElement.querySelector('.line');
    const scrollPart = this.el.nativeElement.querySelector('.bottom-part');
    const scrollInfo = this.el.nativeElement.querySelector('.area-info');
    this.renderer.setStyle(scrollLine, 'left', 25 * index + 5 + '%');
    this.renderer.setStyle(scrollLine, 'transition', '1s');
    if (data[index].companyProjectGroupMode === 4) {
      // if (!this.isFinished) {
      if (this.projectList[index].projectList.length / 4 > 3) {
        this.isLess = false;
        this.canRun = true;
        this.renderer.setStyle(scrollPart, 'touch-action', 'none');
      } else {
        this.canRun = false;
        this.isLess = true;
        this.renderer.setStyle(scrollPart, 'touch-action', 'inherit');
        this.renderer.setStyle(scrollInfo, 'touch-action', 'inherit');
      }
      // }
    } else {
      if (this.projectList[index].groups.length / 4 > 3) {
        this.isLess = false;
        this.canRun = true;
        this.renderer.setStyle(scrollPart, 'touch-action', 'none');
      } else {
        this.canRun = false;
        this.isLess = true;
        this.renderer.setStyle(scrollPart, 'touch-action', 'inherit');
        this.renderer.setStyle(scrollInfo, 'touch-action', 'inherit');
      }
      // }
    }
    if (data.length > 4) {
      if (index >= 2 && (data.length - 1) > index) {
        this.renderer.setStyle(scrollElm, 'left', -scrollModule.offsetWidth * (index - 2) + 'px');
        this.renderer.setStyle(scrollElm, 'transition', '1s');
      }
    }
  }

  // 文字处理
  WordResult() {
    // 计算内容的高度 来判断是多少行
    const wareNameText = [];
    const heightSome = [];
    const wareName = this.el.nativeElement.querySelectorAll('.each-name');
    for (let i = 0; i < wareName.length; i++) {
      wareNameText[i] = wareName[i].innerHTML;
      heightSome[i] = wareName[i].clientHeight;
      if (heightSome[i] > 40) {
        // 这个42数字是两行的时候的高度，根据你设定的字体大小有关
        for (let k = 0; heightSome[i] > 40; k++) {
          // 每次删掉最后一个然后返回
          wareNameText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1);
          // 重新返回的字符在写在span里面 ，计算新的高度
          wareName[i].innerHTML = wareNameText[i];
          heightSome[i] = wareName[i].clientHeight;
        }
        // 得到正好符合高度的字符，删除最后一个变为省略号 填充在页面里
        const newText = [];
        newText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1) + '...';
        wareName[i].innerHTML = newText[i];
      }
    }
  }

  // 监听页面滑动
  logScrolling(e) {
    if (this.isFinished) {
      if (e.detail.scrollTop === 0) {
        this.isDown = true;
        this.bodyActive = false;
        this.isSelected = false;
        const partElm = this.el.nativeElement.querySelector('.bottom-part');
        const infoElm = this.el.nativeElement.querySelector('.area-info');
        this.renderer.setStyle(partElm, 'touch-action', 'none');
        this.renderer.setStyle(infoElm, 'touch-action', 'none');
      } else {
        this.isDown = false;
        this.bodyActive = true;
        this.isSelected = true;
        this.shadowActive = true;
      }
    }
  }

  showMore() {
    this.canGoBack = false;
    this.isDown = true;
    this.isFinished = true;
    this.headerActive = true;
    // this.contentActive = true;
    // this.bodyActive = true;
    const contentElm = this.el.nativeElement.querySelector('.ion-content');
    const bgElm = this.el.nativeElement.querySelector('.bg-top');
    const topElm = this.el.nativeElement.querySelector('.area-top');
    const titleElm = this.el.nativeElement.querySelector('.area-title');
    const lineElm = this.el.nativeElement.querySelector('.area-Line');
    const partElm = this.el.nativeElement.querySelector('.bottom-part');
    const proElm = this.el.nativeElement.querySelectorAll('.area-project');
    const infoElm = this.el.nativeElement.querySelector('.area-info');
    const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    const hrHight = lineElm ? lineElm.offsetHeight : 0;
    const scrollHeight = parseInt(bgElm.offsetHeight + topElm.offsetHeight + titleElm.offsetHeight + hrHight, 10) - 84;
    this.renderer.setAttribute(contentElm, 'scroll-y', 'true');
    this.renderer.setStyle(contentElm, 'top', '-' + scrollHeight + 'px');
    this.renderer.setStyle(contentElm, 'transition', '2s');
    this.renderer.setStyle(contentElm, 'min-height', + h + 321 - 60 + 'px');
    this.renderer.setStyle(partElm, 'touch-action', 'inherit');
    this.renderer.setStyle(infoElm, 'touch-action', 'inherit');
    for (const data of proElm) {
      this.renderer.setStyle(data, 'touch-action', 'inherit');
      this.renderer.setStyle(data, 'overflow-y', 'auto');
    }
  }

  showLess(e) {
    this.isFinished = false;
    this.canGoBack = true;
    this.bodyActive = false;
    this.headerActive = false;
    this.shadowActive = false;
    this.isSelected = false;
    const contentElm = this.el.nativeElement.querySelector('.ion-content');
    const headerElm = this.el.nativeElement.querySelector('.ion-header');
    const proElm = this.el.nativeElement.querySelectorAll('.area-project');
    const partElm = this.el.nativeElement.querySelector('.bottom-part');
    const infoElm = this.el.nativeElement.querySelector('.area-info');
    this.renderer.setStyle(contentElm, 'top', '0');
    this.renderer.setStyle(contentElm, 'transition', '2s');
    this.renderer.setAttribute(contentElm, 'scroll-y', 'false');
    this.renderer.setStyle(headerElm, 'transition', '2s');
    // 如果是项目少的情况下
    if (this.isLess) {
      this.renderer.setStyle(partElm, 'touch-action', 'inherit');
      this.renderer.setStyle(infoElm, 'touch-action', 'inherit');
    } else {
      this.renderer.setStyle(partElm, 'touch-action', 'none');
    }
    for (const data of proElm) {
      this.renderer.setStyle(data, 'touch-action', 'none');
    }
    setTimeout(() => {
      this.contentActive = false;
    }, 2000)
  }

  goBack() {
    this.navCtrl.pop();
  }

  Move() {
    const scrollElm = this.el.nativeElement.querySelector('.area-region');
    const scrollModule = this.el.nativeElement.querySelector('.region-module');
    scrollElm.style.left = 0;
    let scrollLeft;
    const Elm = new Hammer(scrollElm);
    Elm.on('panstart', (event) => {
      scrollLeft = parseFloat(scrollElm.style.left.substring(0, scrollElm.style.left.length - 2));
    })

    Elm.on('panmove', (event) => {
      this.renderer.setStyle(scrollElm, 'transition', '0s');
      scrollElm.style.left = scrollLeft + event.deltaX + 'px';
      const scroll = parseFloat(scrollElm.style.left.substring(0, scrollElm.style.left.length - 2))
      if (scroll > 0) {
        scrollElm.style.left = '0px';
      }
      const scrollMax = -(this.projectList.length - 4) * scrollModule.offsetWidth;
      if (scroll < scrollMax) {
        scrollElm.style.left = scrollMax + 'px';
      }
    })

  }

}
